<?php

declare(strict_types=1);

namespace App\Model;

use Hyperf\DbConnection\Model\Model;
use Hyperf\Cache\Annotation\Cacheable;

/**
 *  通话挂断记录
 */
class CallHangup extends Model
{
    protected $table = 'call_hangup';

    /**
     * 添加记录
     */
    static function addRecord($userId = 0, $chatUserId = 0, $callInfo = null, $callType = 0)
    {
        $model = new self();
        $model->user_id = $userId;
        $model->chat_user_id = $chatUserId;
        $model->call_id = $callInfo ? $callInfo->id : 0;
        $model->call_from = $callInfo ? $callInfo->from : 0;
        $model->call_type = $callType;
        return $model->saveOrFail() ? 1 : 0;
    }

    /**
     * 最近有挂断chatUserId的用户
     */
    static function latestRecords($chatUserId = 0, $minuts = 3)
    {
        $where = [];
        $chatUserId && $where[] = ['chat_user_id', $chatUserId];
        $where[] = ['created_at', '>', date('Y-m-d H:i:00', time() - 60 * $minuts)];
        return array_unique(self::where($where)->pluck('user_id')->toArray());
    }

    /**
     * 挂断
     */
    static function getTodayHangupUsers($minutes = 5)
    {
        //@Cacheable(prefix="hangup_users", ttl=60, value="_#{minutes}", listener="hangup_user_update")
        $where = [];
        $nowMinutes = date('i', time());
        $i = (string)floor($nowMinutes / $minutes) * $minutes;
        $where[] = ['chat_user_id', '>', 0];
        $where[] = ['created_at', '>', date('Y-m-d H:' . $i . ':00')];
        return self::where($where)->pluck('user_id')->toArray();
    }
}
